package cn.edu.seu.ssny.advice;

import cn.edu.seu.ssny.common.R;
import cn.edu.seu.ssny.enums.ResultCodeEnum;
import cn.edu.seu.ssny.exception.SsnyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import java.io.IOException;

@Slf4j
@RestControllerAdvice
public class GlobalControllerAdvice {

    /**
     * 参数缺少异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public R handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.info(e.getMessage(), e);
        return R.error().message("缺乏参数:" + e.getParameterName());
    }

    /**
     * 参数缺少异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MissingServletRequestPartException.class})
    public R handleMissingServletRequestPartException(MissingServletRequestPartException e) {
        log.info(e.getMessage(), e);
        return R.error().message("缺乏参数:" + e.getRequestPartName());
    }

    /**
     * 参数格式异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentTypeMismatchException(MethodArgumentNotValidException e) {
        log.info(e.getMessage(), e);
        return R.error().message("参数类型不匹配:" + e.getParameter().getParameterName());
    }

    /**
     * 参数格式异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public R handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.info(e.getMessage(), e);
        return R.error().message("参数类型不匹配:" + e.getParameter().getParameterName());
    }


    @ExceptionHandler(SsnyException.class)
    public R handleSsnyException(SsnyException e) {
        log.error(e.getMessage(), e);
        return R.error().message(e.getMessage()).code(e.getCode());
    }

    @ExceptionHandler(IOException.class)
    public R handleIOException(IOException e) {
        log.error(e.getMessage(), e);
        return R.result(ResultCodeEnum.ERROR_IOEXCEPTION);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        log.info(e.getMessage(), e);
        e.printStackTrace();
        return R.error();
    }

}
